package com.example.lastwork2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


import com.example.lastwork2.detail.HomeActivity;
import com.example.lastwork2.fragments.detail.ShopDetailActivity;
import com.example.lastwork2.model.Order;
import com.example.lastwork2.model.User;
import com.example.lastwork2.register.RegisterActivity;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    //全局变量存储当前登录的用户ID
    public static String userId;


    //当前登录用户
    public static User onUser;
    //用户名
    private TextView userName;
    //密码
    private TextView userPwd;
    //登录
    private Button btnLogin;
    //注册
    private TextView tvRegister;


    private Handler handler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //绑定控件
        getView();



        //登录功能
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将输入框中的用户名传到服务器,返回一个User对象
                String username = userName.getText().toString();
                String password = userPwd.getText().toString();
                System.out.println("username:"+username);
                System.out.println("password:"+password);
                if(username.equals("") || password.equals("")){
                    //弹窗用户名或密码为空
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("登录失败")
                            .setMessage("用户名或密码为空")
                            .show();
                }else{
                    sendToServer(username);
                    handler = new Handler(Looper.getMainLooper()){
                        @Override
                        public void handleMessage(@NonNull Message msg) {
                            //判断msg的what
                            switch (msg.what){
                                case -1:
                                    //弹窗用户名或密码错误 实际上是用户名不存在
                                    new AlertDialog.Builder(MainActivity.this)
                                            .setTitle("登录失败")
                                            .setMessage("用户名或密码错误")
                                            .show();
                                    break;
                                case 1:
                                    //获取真实密码
                                    String pwd = (String) msg.obj;
                                    //idea返回用户名和密码是否正确
                                    //如果正确则跳转到内容详情页
                                    //如果不正确则弹窗用户名或密码不正确
                                    if(pwd.equals(password)){

                                        ShopDetailActivity.cartShop = new ArrayList<>();
                                        ShopDetailActivity.curnum = new ArrayList<>();

                                        //跳转首页
                                        Intent intent = new Intent();
                                        intent.setClass(
                                                MainActivity.this,
                                                HomeActivity.class
                                        );
                                        startActivity(intent);

                                    }else{
                                        //弹窗用户名或密码错误
                                        new AlertDialog.Builder(MainActivity.this)
                                                .setTitle("登录失败")
                                                .setMessage("用户名或密码错误")
                                                .show();
                                    }

                                    break;
                            }
                        }
                    };
                }


            }
        });

        //注册跳转
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到注册页面   具体逻辑在registerActivity里面写
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,
                        RegisterActivity.class);
                startActivity(intent);
            }
        });


    }



    //（登录功能） 判断将用户名和密码传到服务器
    private void sendToServer(String username) {

        String url1 = "http://10.0.2.2:8080/bigwork/login";


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //发送的数据格式
                    String value = "?username=";
                    //通过指定URL向服务器发送数据
                    URL url = new URL(url1+value+username);
                    URLConnection urlConnection = url.openConnection();

                    //接受服务器传来的数据
                    InputStream inputStream = urlConnection.getInputStream();
                    //创建字符流读取数据
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    String str = bufferedReader.readLine();

                    //服务器发送json数据成功
                    System.out.println(str);

                    //关闭流
                    bufferedReader.close();
                    inputStream.close();

                    //将json数据解析
                    Gson gson = new Gson();
                    User user = gson.fromJson(str,User.class);

                    //存储当前用户
                    onUser = new User();
                    onUser.setUserId(user.getUserId());
                    onUser.setUsername(user.getUsername());
                    onUser.setPassword(user.getPassword());

                    //利用Message+handler将数据发送至主线程
                    if (user.getUserId()!=-1){
                        userId = String.valueOf(user.getUserId());
                        Message msg = handler.obtainMessage();
                        msg.what = 1;
                        msg.obj = user.getPassword();
                        handler.sendMessage(msg);
                    }else{
                        Message msg = handler.obtainMessage();
                        msg.what = -1;
                        handler.sendMessage(msg);
                    }




                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();


    }


    //获取控件
    private void getView() {
        userName = findViewById(R.id.user_name);
        userPwd = findViewById(R.id.user_password);
        btnLogin = findViewById(R.id.login);
        tvRegister = findViewById(R.id.register);

    }
}